import { Injectable } from '@nestjs/common';
import { PermissionEntity } from './entities/permission.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { ListPermissionReturn } from './dto/list-permission.dto';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(PermissionEntity)
    private readonly permissionRepository: Repository<PermissionEntity>,
  ) {}

  async create(
    createPermissionDto: CreatePermissionDto,
  ): Promise<PermissionEntity> {
    let permissionItem = this.permissionRepository.create(createPermissionDto);
    permissionItem = await this.permissionRepository.save(permissionItem);
    return await this.findOne(permissionItem.id);
  }

  async findAll(): Promise<ListPermissionReturn> {
    const [rows, total] = await this.permissionRepository.findAndCount();

    return {
      total,
      rows,
    };
  }

  async findOne(id: string): Promise<PermissionEntity> {
    const permissionItem = await this.permissionRepository.findOne({
      where: { id },
    });
    return permissionItem;
  }

  async update(
    id: string,
    updatePermissionDto: UpdatePermissionDto,
  ): Promise<string> {
    await this.permissionRepository.update(id, updatePermissionDto);
    return 'success';
  }

  async remove(id: string): Promise<string> {
    await this.permissionRepository.softDelete(id);
    return 'success';
  }
}
